import plugin from '../../lib/plugins/plugin.js';

const roar_key_arr = ["喵", "呜", "啊", "~"];

export class Roar extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: '兽音译者',
            /** 功能描述 */
            dsc: '兽音译者',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 5000,
            rule: [
                {
                    /** 命令正则匹配 */
                    reg: "^#?喵语(加密|翻译).*$",
                    /** 执行方法 */
                    fnc: 'roar',
                },
            ]
        })
    }

    async roar(e) {
        let msg = e.msg.replace(/#?喵语(加密|翻译)/, "").trim();
        await e.reply(msg ? (e.msg.includes("加密") ? roar_encode(msg) : roar_decode(msg)) : `请输入要${e.msg.includes("加密") ? "加密" : "翻译"}的文本`);
        return true;
    }
}

function roar_encode(string) {
    let d = "";
    for (let i = 0; i < string.length; i++) {
        let each_char = string.charCodeAt(i);
        d += each_char.toString(16).padStart(4, '0');
    }

    let b = "";
    for (let a = 0; a < d.length; a++) {
        let x = d[a];
        let c = parseInt(x, 16) + a % 16;
        if (c >= 16) {
            c -= 16;
        }
        b += roar_key_arr[Math.floor(c / 4)] + roar_key_arr[c % 4];
    }
    let result = roar_key_arr[3] + roar_key_arr[1] + roar_key_arr[0] + b + roar_key_arr[2];
    return result;
}

function roar_decode(string) {
    if (string.length < 4) {
        return "";
    }
    let c = roar_key_arr;
    let a = string.slice(3, -1);

    let d = "";
    let b = a;
    for (let e = 0; e < a.length; e += 2) {
        let f = 0;
        let g = b[e];
        while (f <= 3 && g !== c[f]) {
            g = b[e];
            f += 1;
        }
        let h = 0;
        g = b[e + 1];
        while (h <= 3 && g !== c[h]) {
            g = b[e + 1];
            h += 1;
        }

        g = 4 * f + h - Math.floor(e / 2) % 16;
        if (g < 0) {
            g += 16;
        }
        d += g.toString(16);
    }
    let a_decoded = "";
    for (let start_ind = 0; start_ind < d.length; start_ind += 4) {
        let e = d.substring(start_ind, start_ind + 4);
        a_decoded += String.fromCharCode(parseInt(e, 16));
    }

    return a_decoded;
}